package openjdk.collections.map;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * nked hash map
 */
public class LinkedHashMapDemo {

    static Map<String, String> map = new HashMap<>();
    static {
        map.put("a","a");
        map.put("f","f");
        map.put("c","c");
        map.put("g","g");
        map.put("e","e");
        map.put("A","A");
    }

    public static void main(String[] args) {
        LinkedHashMap<String,String> linked = reLink(map);
        linked.forEach((k,v)->{
            System.out.println(k.concat(" : ").concat(v));
        });
    }

    private static LinkedHashMap<String, String> reLink(Map<String,String> maps) {

        final LinkedHashMap<String, String> sortedByCount = map.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));

        // reversed()
        final LinkedHashMap<String, String> sortedByCount1 = map.entrySet()
                .stream()
                .sorted((Map.Entry.<String, String>comparingByValue().reversed()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));


        return sortedByCount;
    }


    private static LinkedHashMap<String, String> reLink2(Map<String,String> maps) {

        final LinkedHashMap<String, String> sortedByCount3 = map.entrySet()
                .stream()
                .sorted((e1, e2) -> e1.getValue().compareTo(e2.getValue()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));


        //reversed()
        final LinkedHashMap<String, String> sortedByCount2 = map.entrySet()
                .stream()
                .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
        return sortedByCount3;
    }

}
